<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="70%"
    @ok="handleSubmit"
  >
    <a-card title="活动详情" :bordered="false">
      <BasicForm @register="registerForm">
        <template #add="{ field }">
          <Button v-if="Number(field) === 0" @click="addScheduleFieldRow(0)">+</Button>
          <Button v-if="field > 0" @click="delScheduleFieldRow(field)">-</Button>
        </template>
      </BasicForm>
      <BasicForm @register="registerExpertForm">
        <template #add="{ field }">
          <Button v-if="Number(field) === 0" @click="addExpertFieldRow(0)">+</Button>
          <Button v-if="field > 0" @click="delExpertFieldRow(field)">-</Button>
        </template>
      </BasicForm>
    </a-card>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, formExpertSchema } from './websiteActivityTableData';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Card } from 'ant-design-vue';
  import { Button } from '/@/components/Button';
  import { PageWrapper } from '/@/components/Page';
  import {
    websiteActivitySaveApi,
    websiteActivityUpdateApi,
  } from '/@/api/website/websiteActivityApi';
  import dotenv from 'dotenv';
  import fs from 'fs';
  import path from 'path';
  import { websiteExpertListApi } from '/@/api/website/websiteExpertApi';
  import {formatToDateTime} from "/@/utils/dateUtil";

  export default defineComponent({
    name: 'WebsiteActivityDrawer.vueDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      [Card.name]: Card,
      Button,
      PageWrapper,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);

      const activityId = ref('');

      const n = ref(1);
      const expertFieldIndex = ref(1);

      const [
        registerForm,
        {
          resetFields,
          setFieldsValue,
          validate,
          appendSchemaByField,
          removeSchemaByFiled,
          getFieldsValue,
        },
      ] = useForm({
        labelWidth: 150,
        schemas: formSchema,

        showActionButtonGroup: false,
        actionColOptions: { span: 24 },
        baseColProps: { lg: 24, md: 24 },
      });

      const [
        registerExpertForm,
        {
          resetFields: resetExpertFields,
          setFieldsValue: setExpertFieldsValue,
          validate: validateExpert,
          appendSchemaByField: appendExpertSchemaByField,
          removeSchemaByFiled: removeExpertSchemaByFiled,
          getFieldsValue: getExpertFieldsValue,
        },
      ] = useForm({
        labelWidth: 150,
        schemas: formExpertSchema,

        showActionButtonGroup: false,
        actionColOptions: { span: 24 },
        baseColProps: { lg: 24, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        resetExpertFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        activityId.value = data?.data?.activityId;
        if (unref(isUpdate)) {
          if (data.data.advanceNoticeImage) {
            data.data.advanceNoticeImage = [data.data.advanceNoticeImage];
          }
          if (data.data.coverImage) {
            data.data.coverImage = [data.data.coverImage];
          }

          data.data.activityTime = [data.data.activityBeginTime , data.data.activityEndTime]
          console.log( data.data);
          if (data.data.activityScheduleList && data.data.activityScheduleList.length > 0) {
            //生成cad 动态行字段，并进行赋值
            for (let i = 0; i < data.data.activityScheduleList.length; i++) {
              let item = data.data.activityScheduleList[i];

              if (i !== 0) {
                delScheduleFieldRow(i);
                addScheduleFieldRow(i);
              }
              console.log('nvalue:' + n.value);

              data.data['scheduleName' + i] = item.scheduleName;
              data.data['scheduleBrief' + i] = item.scheduleBrief;
              data.data['scheduleBeginTime' + i] = item.scheduleBeginTime;
              data.data['scheduleEndTime' + i] = item.scheduleEndTime;
              data.data['indexOrder' + i] = item.indexOrder;
            }
          }

          if (data.data.activityExpertList && data.data.activityExpertList.length > 0) {
            //生成cad 动态行字段，并进行赋值
            for (let i = 0; i < data.data.activityExpertList.length; i++) {
              let item = data.data.activityExpertList[i];

              if (i !== 0) {
                delExpertFieldRow(i);
                addExpertFieldRow(i);
              }
              console.log('nvalue:' + expertFieldIndex.value);

              data.data['expertId' + i] = item.expertId;
              data.data['indexOrder' + i] = item.indexOrder;
            }
          }

          setFieldsValue({
            ...data.data,
          });
          setExpertFieldsValue({
            ...data.data,
          });
        }
        /*updateSchema({
    field: 'parentMenu',
    componentProps: {  },
  });*/
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          const expertValues = await validateExpert();
          values.activityBeginTime = formatToDateTime(values.activityTime[0]);
          values.activityEndTime = formatToDateTime(values.activityTime[1]);
          values.activityId = activityId.value;
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          if (values.advanceNoticeImage) values.advanceNoticeImage = values.advanceNoticeImage[0];
          if (values.coverImage) values.coverImage = values.coverImage[0];

          const activityScheduleList: any[] = [];
          //封装日程维护信息
          if (n.value && n.value > 0) {
            for (let i = 0; i < n.value; i++) {
              console.log('scheduleName' + i);
              if (values['scheduleName' + i]) {
                activityScheduleList.push({
                  scheduleName: values['scheduleName' + i],
                  scheduleBrief: values['scheduleBrief' + i],
                  scheduleBeginTime: formatToDateTime(values['scheduleBeginTime' + i]),
                  scheduleEndTime: formatToDateTime(values['scheduleEndTime' + i]),
                  indexOrder: values['indexOrder' + i],
                });
              }
            }
          }
          values.websiteActivityScheduleList = activityScheduleList;
          console.log(values);

          const activityExpertList: any[] = [];
          //封装专家维护信息
          if (expertFieldIndex.value && expertFieldIndex.value > 0) {
            for (let i = 0; i < expertFieldIndex.value; i++) {
              console.log('expertId' + i);
              if (expertValues['expertId' + i]) {
                activityExpertList.push({
                  expertId: expertValues['expertId' + i],
                  indexOrder: expertValues['indexOrder' + i],
                });
              }
            }
          }
          values.websiteActivityExpertMaps = activityExpertList;

          await (!unref(isUpdate)
            ? websiteActivitySaveApi(values)
            : websiteActivityUpdateApi(values));
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      function addScheduleFieldRow(index) {
        console.log(index);
        let sequence = n.value;
        if (index > 0) {
          sequence = index;
        }
        appendSchemaByField(
          {
            field: `scheduleName${sequence}`,
            component: 'Input',
            label: '日程名称',
            colProps: {
              lg: 12,
              md: 12,
            },
            required: true,
          },
          '',
        );

        appendSchemaByField(
          {
            field: `scheduleBeginTime${sequence}`,
            component: 'TimePicker',
            label: '开始时间',
            colProps: {
              lg: 6,
              md: 6,
            },
            required: true,
          },
          '',
        );
        appendSchemaByField(
          {
            field: `scheduleEndTime${sequence}`,
            component: 'TimePicker',
            label: '结束时间',
            colProps: {
              lg: 6,
              md: 6,
            },
            required: true,
          },
          '',
        );
        appendSchemaByField(
          {
            field: `scheduleBrief${sequence}`,
            component: 'InputTextArea',
            label: '日程简介',
            colProps: {
              lg: 18,
              md: 18,
            },
            required: true,
          },
          '',
        );
        appendSchemaByField(
          {
            field: `indexOrder${sequence}`,
            component: 'InputNumber',
            label: '排序',
            colProps: {
              lg: 4,
              md: 4,
            },
          },
          '',
        );

        appendSchemaByField(
          {
            field: `${sequence}`,
            component: 'Input',
            label: ' ',
            colProps: {
              lg: 2,
              md: 2,
            },
            slot: 'add',
          },
          '',
        );
        console.log('11n.value ' + n.value);
        if (index != 0) {
          n.value = index + 1;
        } else {
          n.value++;
        }
        console.log('n.value ' + n.value);
      }

      function delScheduleFieldRow(field) {
        removeSchemaByFiled([
          `scheduleName${field}`,
          `scheduleBrief${field}`,
          `scheduleBeginTime${field}`,
          `scheduleEndTime${field}`,
          `indexOrder${field}`,
          `${field}`,
        ]);
        n.value--;
      }

      function addExpertFieldRow(index) {
        console.log(index);
        let sequence = expertFieldIndex.value;
        if (index > 0) {
          sequence = index;
        }

        appendExpertSchemaByField(
          {
            field: `expertId${sequence}`,
            component: 'ApiSelect',
            componentProps: {
              api: websiteExpertListApi,
              labelField: 'expertName',
              valueField: 'expertId',
            },
            label: '专家/嘉宾',
            colProps: {
              lg: 10,
              md: 10,
            },
          },
          '',
        );
        appendExpertSchemaByField(
          {
            field: `indexOrder${sequence}`,
            component: 'InputNumber',
            label: '日程排序',
            colProps: {
              lg: 10,
              md: 10,
            },
          },
          '',
        );

        appendExpertSchemaByField(
          {
            field: `${sequence}`,
            component: 'Input',
            label: ' ',
            colProps: {
              lg: 4,
              md: 4,
            },
            slot: 'add',
          },
          '',
        );
        console.log('11expertFieldIndex.value ' + expertFieldIndex.value);
        if (index != 0) {
          expertFieldIndex.value = index + 1;
        } else {
          expertFieldIndex.value++;
        }
        console.log('expertFieldIndex.value ' + expertFieldIndex.value);
      }

      function delExpertFieldRow(field) {
        removeExpertSchemaByFiled([`expertId${field}`, `indexOrder${field}`, `${field}`]);
        expertFieldIndex.value--;
      }

      return {
        registerDrawer,
        registerForm,
        registerExpertForm,
        getTitle,
        handleSubmit,
        delScheduleFieldRow,
        addScheduleFieldRow,
        delExpertFieldRow,
        addExpertFieldRow,
      };
    },
  });
</script>
